const Service = require("egg").Service;
const bcrypt = require("bcryptjs");

class UserService extends Service {
  // 默认不需要提供构造函数。
  // constructor(ctx) {
  //   super(ctx); 如果需要在构造函数做一些处理，一定要有这句话，才能保证后面 `this.ctx`的使用。
  //   // 就可以直接通过 this.ctx 获取 ctx 了
  //   // 还可以直接通过 this.app 获取 app 了
  // }

  // 查询用户信息
  async find(uid) {
    const { ctx } = this;
    const user = await ctx.model.Admin.findOne({
      where: {
        id: uid,
      },
    });
    return {
      nickname: user.nickname,
      email: user.email,
    };
  }

  // 验证密码
  async verify(params) {
    const { ctx } = this;
    const { email, password } = params;
    const admin = await ctx.model.Admin.findOne({
      where: {
        email,
      },
    });
    if (!admin) {
      throw "账号不存在";
    }
    const correct = bcrypt.compareSync(password, admin.password);
    if (!correct) {
      throw "账号或密码不正确";
    }
    return admin;
  }

  // 创建账号
  async create(params) {
    const { ctx } = this;
    const { nickname, email, password } = params;
    const hasAdmin = await ctx.model.Admin.findOne({
      where: {
        email,
      },
    });
    if (hasAdmin) {
      throw "账号已存在";
    }
    var admin = new ctx.model.Admin();
    admin.email = email;
    admin.nickname = nickname;
    admin.password = password;
    await admin.save();
    return {
      email,
      nickname,
    };
  }
}
module.exports = UserService;
